﻿using DongFangGuoKai.WMSPlatform.Commn.ApiResultModule;
using DongFangGuoKai.WMSPlatform.Commn.ExtendModule;
using DongFangGuoKai.WMSPlatform.Core;
using DongFangGuoKai.WMSPlatform.Domain.Model;
using DongFangGuoKai.WMSPlatform.Service.InboundOrderDetail;
using DongFangGuoKai.WMSPlatform.Service.InboundOrderDetail.DTO;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Serilog;
using System.Security.Claims;

namespace DongFangGuoKai.WMSPlatform.WebApi.Controllers.OrderInBusiness
{
    
    /// <summary>
    /// 入库模块
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class TReceivingBillController : BaseController
    {
        private readonly ITReceivingOrderDetailService tReceivingOrderDetailService;
        private readonly SimpleRepositroy<TReceivingBills> receivingBillrepost;
        private readonly ILogger<TReceivingBillController> receivingBillogger;
        private readonly SimpleRepositroy<TAreas> areasrepost;
        private readonly SimpleRepositroy<TCells> cellrepost;
        private readonly SimpleRepositroy<TReceivingBillDetails> receivingBillDetailsrepost;
        private readonly SimpleRepositroy<TStackingStorages> stackingStoragesrepost;
        private readonly SimpleRepositroy<TReceivingOrderDetails> rceivingOrderDetailsrepost;

        public TReceivingBillController(ITReceivingOrderDetailService tReceivingOrderDetailService,
            SimpleRepositroy<TReceivingBills> receivingBillrepost,
            ILogger<TReceivingBillController> receivingBillogger
            )
        {
            this.tReceivingOrderDetailService = tReceivingOrderDetailService;
            this.receivingBillrepost = receivingBillrepost;
            this.receivingBillogger = receivingBillogger;
            areasrepost = receivingBillrepost.ChangeRepository<SimpleRepositroy<TAreas>>();
            cellrepost = receivingBillrepost.ChangeRepository<SimpleRepositroy<TCells>>();
            receivingBillDetailsrepost = receivingBillrepost.ChangeRepository<SimpleRepositroy<TReceivingBillDetails>>();
            stackingStoragesrepost = receivingBillrepost.ChangeRepository<SimpleRepositroy<TStackingStorages>>();
            rceivingOrderDetailsrepost = receivingBillrepost.ChangeRepository<SimpleRepositroy<TReceivingOrderDetails>>();

        }
        #region PC接口

        /// <summary>
        /// 查询验收单
        /// </summary>
        /// <param name="billNo"></param>
        /// <param name="status"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetReceivingBillList(string? billNo, int status = 3, int pageIndex = 1, int pageSize = 10)
        {
            if (pageIndex <= 0 || pageSize <= 0)
            {
                return Failed("分页条件有误！");
            }
            int totalCount;

            var list = tReceivingOrderDetailService.GetReceivingBillList(billNo, status, pageIndex, pageSize, out totalCount);

            if (list != null)
            {
                return Success(list,  totalCount ,"查询成功");
            }
            return Failed("查询失败！");
        }

        /// <summary>
        /// 修改状态
        /// </summary>
        /// <param name="rid"></param>
        /// <returns></returns>
        [HttpPut]
        public IActionResult UpdReceivingBillStatus(int rid)
        {
            if (rid <= 0)
            {
                return Failed( "Id有误！");
            }
            bool IsOK = tReceivingOrderDetailService.UpdReceivingBillStatus(rid);
            if (IsOK)
            {
                return Success("保存成功！");
            }
            return Failed("保存失败！");
        }

        /// <summary>
        /// RFID添加收货单（海宁）
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult AddCheck(AddReceivingBilDTO addReceivingBilDTO)
        {
            var IsOk = tReceivingOrderDetailService.AddCheck(addReceivingBilDTO, out string Message);
            if (IsOk)
            {
                receivingBillogger.LogInformation("添加收货单成功，" + Message + ",入参为" + addReceivingBilDTO.ToJson());
                return Success("保存成功！");
            }
            receivingBillogger.LogError("添加收货单失败，" + Message + ",入参为" + addReceivingBilDTO.ToJson());
            return Failed( Message);
        }

        /// <summary>
        /// 返回验收单下的所有物料条码（海宁）
        /// </summary>
        /// <param name="ChackNumber"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetCheckMaterialCode(string ChackNumber)
        {
            var receivingBill = tReceivingOrderDetailService.GetCheckMaterialCode(ChackNumber);
            if (receivingBill is null)
            {
                return Failed("未查询出单子信息！");
            }
            var data = receivingBill.BillDetailList.Select(r => new
            {
                r.MaterialCode,
                r.MaterialName,
                r.BatchNo,
                r.materialNorms,
                r.BillNo
            });
            if (data is null || data.Count() == 0)
            {
                return Failed("生成失败未查出物料！");
            }
            return Success(data,"查询成功！");
        }


        /// <summary>
        /// 修改收货单状态（已提交 海宁）
        /// </summary>
        /// <param name="checkNumber"></param>
        /// <param name="orderIds"></param>
        /// <returns></returns>
        [HttpPut]
        public IActionResult UpdateReceivingBillStatus(string checkNumber, string orderIds)
        {
            if (string.IsNullOrEmpty(checkNumber) || string.IsNullOrEmpty(orderIds))
            {
                return Failed("参数有误");
            }
            var IsOk = tReceivingOrderDetailService.UpdateReceivingBillStatus(checkNumber, orderIds,out string Msg);
            if (IsOk)
            {
                receivingBillogger.LogInformation("提交收货单成功，" + Msg + ",入参为" + checkNumber + "," +orderIds);
                return Success(Msg);
            }
            receivingBillogger.LogError("提交收货单失败，" + Msg + ",入参为" + checkNumber + "," + orderIds);
            return Failed(Msg);
        }

        /// <summary>
        /// 获取提交入库的数据(海宁)
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetCheck()
        {
            var data = tReceivingOrderDetailService.GetSubmitOutList().FirstOrDefault();
            if (data is null)
            {
                return Success(data, "没有到数据");
            }
            return Success(data, "查询成功");
        }


        /// <summary>
        /// 显示入库单列表
        /// </summary>
        /// <param name="billType"></param>
        /// <param name="status"></param>
        /// <param name="warehouseid"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="totalCount"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetReceivingOrderDetailList(string? orderSn, int billType, int status, int warehouseid, int pageIndex, int pageSize)
        {
            if (pageIndex <= 0 || pageSize <= 0)
            {
                return Failed("分页参数有误!", 400);
            }
            int totalCount;

            var list = tReceivingOrderDetailService.GetReceivingOrderDetailList(orderSn, billType, status, warehouseid, pageIndex, pageSize, out totalCount);

            if (list != null)
            {
                return Success(list, totalCount, "查询成功！");
            }
            return Failed("查询失败！");
        }


        #endregion

        #region PDA接口
        /// <summary>
        /// pda查询验收单
        /// </summary>
        /// <param name="supplierId"></param>
        /// <param name="status"></param>
        /// <param name="warehouseId"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult PDAGetReceivingBillList(string? key, int pageIndex = 1, int pageSize = 10)
        {
            if (pageIndex <= 0 || pageSize <= 0)
            {
                return Failed("分页条件有误！");
            }
            int totalCount;

            var list = tReceivingOrderDetailService.PDAGetReceivingBillList(key, pageIndex, pageSize, out totalCount);

            if (list != null)
            {
                return Success(list, totalCount, "查询成功");
            }
            return Failed("未查询到入库信息！");
        }


        /// <summary>
        /// 查询入库单
        /// </summary>
        /// <param name="PalletCode"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetReceivingBill(string PalletCode)
        {
            var stackingStorages = stackingStoragesrepost.GetList(s => s.Status == 1 && s.PalletBarcode == PalletCode).ToList();
            List<OrderDetailDataDTO> orderdata = new List<OrderDetailDataDTO>();
            foreach (var stackingStorage in stackingStorages)
            {
                var orderDetail = rceivingOrderDetailsrepost.GetFirst(x => x.Id == stackingStorage.RelatedOrderDetailId);
                if (orderDetail is null)
                {
                    return Success(orderdata, "入库单查询失败");
                }
                orderdata.Add(new OrderDetailDataDTO()
                {
                    OrderDetailId = orderDetail.Id,
                    PallteCode = stackingStorage.PalletBarcode,
                    cell = stackingStorage.ExpectedLocation,
                    OrderNo = orderDetail.OrderSn,
                    MaterialCode = orderDetail.MaterialCode,
                    Num = orderDetail.StackedQty,
                });
            }
            return Success(orderdata, "成功");
        }

        /// <summary>
        /// PDA收货入库(可以组多个物料 海宁)
        /// </summary>
        /// <param name="m"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult BuildCreateStackingStorageMaterials(ReceivingBillOrderMaterialsDto m)
        {
            string message = "";
            try
            {
                if (m.Id <= 0)
                {
                    return Failed("Id有误！");
                }
                if (m.ReceivingBillOrderMaterialsDetailDto.Count <= 0)
                {
                    return Failed("组垛明细有误");
                }
                m.NowUserId = Convert.ToInt32(HttpContext.User.FindFirstValue("Id"));
                m.NowUserRealName = HttpContext.User.FindFirstValue("UserName");

                bool IsOK = tReceivingOrderDetailService.BuildCreateStackingStorageMaterials(m, out message);
                if (IsOK)
                {
                    receivingBillogger.LogInformation("PDA收货入库成功，" + message + ",入参为" + m.ToJson());
                    return Success("保存成功！");
                }
                receivingBillogger.LogError("PDA收货入库失败，" + message + ",入参为" + m.ToJson());
                return Failed(message);
            }
            catch (Exception ex)
            {
                return Failed("保存失败，" + ex.Message);
            }
        }

        /// <summary>
        /// 查询全部库区
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetAreaList()
        {
            var list = areasrepost.GetList();
            if (list.Count() <= 0)
            {
                return Failed("查询失败!");
            }
            return Success(list, "查询成功!");
        }

        /// <summary>
        /// 返回货架数据
        /// </summary>
        /// <param name="cellCode"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetCellByCellCode(string cellCode)
        {
            if (string.IsNullOrEmpty(cellCode))
            {
                return Failed("参数有误");
            }
            var cell = cellrepost.GetFirst(s => s.Code == cellCode);
            if (cell == null)
            {
                return Success("没查询到货架");
            }
            //if (!string.IsNullOrEmpty(cellName))
            //{
            //    cellList = cellList.Where(s => s.Name.Contains(cellName)).ToList();
            //}
            //if (!string.IsNullOrEmpty(areascode))
            //{
            //    cellList = cellList.Where(s => s.AreaCode == areascode).ToList();
            //}
            //if (cellList.Count <= 0)
            //{
            //    return Failed("未查询到仓位!");
            //}
            var resCell = new
            {
                Name = cell.Name,
                Code = cell.Code,
                WhId = cell.WhId,
                Erpcode = cell.Erpcode //海宁仓位id
            };
            
            return Success(resCell, "请求成功");
        }

        /// <summary>
        /// 查询收货单的商品 （海宁）
        /// </summary>
        /// <param name="receivingBillId"></param>
        /// <param name="materialCodeArticlebarcode"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetReceivingBillGoodsDeatil(int receivingBillId, string? materialCodeArticlebarcode)
        {
       
            if (receivingBillId <= 0 || materialCodeArticlebarcode is null)
            {
                return Failed("参数有误!");
            }

            var recevingbilldeta = receivingBillDetailsrepost.GetFirst(r => r.BillId == receivingBillId && r.MaterialCode == materialCodeArticlebarcode);

            if (recevingbilldeta is null)
            {
                return Failed("未查出物料!");
            }
            return Success(recevingbilldeta, "查询成功");
        }

        /// <summary>
        /// 入库(多个物料的) （海宁的）
        /// </summary>
        /// <param name="Palletlist">托盘码</param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult ExecCreateMaterialsInventory(string PalletCode)
        {
            if (string.IsNullOrEmpty(PalletCode))
            {
                return Failed("参数有误！");
            }
            try
            {
                var checkin = tReceivingOrderDetailService.ExecCreateMaterials(PalletCode, out string errMsg);
                if (checkin)
                {
                    receivingBillogger.LogInformation("PDA入库成功，" + errMsg + ",入参为" + PalletCode);
                    return Success("入库成功!");
                }
                receivingBillogger.LogError("PDA入库成功，" + errMsg + ",入参为" + PalletCode);
                return Failed( errMsg);
            }
            catch (Exception ex)
            {
                return Failed("入库失败，" + ex.Message);
            }
        }
        #endregion
    }
}
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             